﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using deviceManage.Models;
using deviceManage.vo;
using Microsoft.AspNetCore.WebUtilities;

using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using deviceManage.Service;
using deviceManage.Tools;

namespace deviceManage.Controllers
{
    /// <summary>
    /// 文档管理控制器
    /// </summary>
    public class DocController : Controller
    {
        private readonly DeviceCtx _context;
        private DocumentService docService;
        public DocController(DeviceCtx context)
        {
            _context = context;
            docService = new DocumentService(_context);
        }
               
        
        public  AjaxResult Upload(string key,int category)
        {

            var file = Request.Form.Files;
            long size = file.Sum(f => f.Length);

            // full path to file in temp location
            var filePath = Path.GetTempFileName();

            foreach (var formFile in file)
            {
                if (formFile.Length > 0)
                {
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                         formFile.CopyToAsync(stream);
                        //开始创建doc对象
                        Document doc = new Document();
                        doc.ObjectId = key;
                        doc.Name = formFile.FileName;
                        doc.Category = category;
                        doc.FilePath = filePath;
                        doc.UploadTime = DateTime.Now;
                        //TODO: set upload user
                        //doc.UploadUser = 
                        _context.Document.Add(doc);
                        _context.SaveChanges();
                    }
                }
            }
            return AjaxResult.GetOK("上传成功");
        }

        /// <summary>
        /// 文档管理，上传临时文档，在选择文档类型后统一更新
        /// </summary>        
        public AjaxResult UploadTemp()
        {

            var file = Request.Form.Files;
            long size = file.Sum(f => f.Length);

            // full path to file in temp location
            var filePath = Path.GetTempFileName();
            Document doc = null;
            foreach (var formFile in file)
            {
                if (formFile.Length > 0)
                {
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        formFile.CopyToAsync(stream);
                        //开始创建doc对象
                        doc = new Document();                        
                        doc.Name = formFile.FileName;                        
                        doc.FilePath = filePath;
                        doc.DocState = 1;
                        doc.UploadTime = DateTime.Now;
                        doc.UploadUser =  HttpContext.Session.GetString(WebContext.SESSION_KEY_USER_ID);
                        _context.Document.Add(doc);
                        _context.SaveChanges();                        
                    }
                }
            }
            AjaxResult  result = AjaxResult.GetOK("上传成功");
            List<Document> docList = new List<Document>();
            docList.Add(doc);
            result.Data = docList;
            return result;
        }        


        /// <summary>
        /// Ajax获取某个Object Id的所有的文件
        /// </summary>
        /// <returns></returns>        
        public AjaxResult getAllByObjectId(string id,int? category)
        {

            AjaxResult r = new AjaxResult();

            IQueryable<Document> query = _context.Document.Where(p => p.ObjectId == id);            
            if(category != null && category >= 0)
            {
                query = query.Where(p=>p.Category == category);
            }

            r.Count = query.Count();
            r.Code = 0;
            r.Data = query.OrderByDescending(p => p.UploadTime).ToList();
            return r;
        }

        /// <summary>
        /// 删除附件，delete
        /// </summary>
        /// <returns></returns>
        public AjaxResult Delete(string id)
        {

            var exist = _context.Document.Any(p => p.Id == id);
            if (!exist)
            {
                return AjaxResult.GetError("文件不存在！");
            }
            var doc = _context.Document.Single(p => p.Id == id);
            //首先删除文件
            //System.IO.File.Delete(doc.FilePath);
            //然后删除model
            _context.Remove(doc);
            _context.SaveChanges();

            return AjaxResult.GetOK("操作成功!");

        }

        /// <summary>
        /// 下载文件
        /// </summary>
        public IActionResult Download(string id)
        {
            var doc = _context.Document.Single(p => p.Id == id);            
            var stream = System.IO.File.OpenRead(doc.FilePath);

            string fileExt = System.IO.Path.GetExtension(doc.Name);
            if(fileExt.Length > 0)
            {
                fileExt = fileExt.Substring(1);
            }
             

            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
          //  var memi = provider.Mappings[fileExt];
            return File(stream, "application/*", doc.Name);
        }


        //文档类型管理主页
        public IActionResult DocTypeIndex()
        {
            return View();
        }
        //ajax 获取分页数据，文档类型
        public AjaxResult DocTypeList(int page, int limit, String name)
        {

            AjaxResult r = new AjaxResult();
            IQueryable<DocumentType> q = _context.DocumentType.Where(p => p.Deleted == 0);
            if (!string.IsNullOrWhiteSpace(name))
            {
                q = q.Where(p => p.Name == name);
            }

            r.Count = q.Count();
            r.Code = 0;
            r.Data = q.OrderBy(p => p.SortOrder)
                .Skip((page - 1) * limit).Take(limit)
                .ToList();

            return r;
        }
        //文档类型编辑页面
        public IActionResult DocTypeEdit(string id)
        {
            DocumentType type = new DocumentType();
            if (string.IsNullOrWhiteSpace(id))
            {
                type.Id = System.Guid.NewGuid().ToString();
                type.SortOrder = 100;
            }
            else
            {
                type = _context.DocumentType.Single(p => p.Id == id);
            }

            return View(type);
        }
        
        //保存文档类型
        public AjaxResult SaveDocType(DocumentType type)
        {
            var existName = _context.DocumentType.Any(p => p.Name == type.Name && p.Id != type.Id);
            if (existName)
            {
                return AjaxResult.GetError("名称已经存在！");
            }

            var exist = _context.DocumentType.Any(p => p.Id == type.Id);
            if (!exist)
            {
                type.Deleted = 0;
                _context.DocumentType.Add(type);
                _context.SaveChanges();
            }
            else
            {
                var target = _context.DocumentType.Single(p => p.Id == type.Id);
                target.Name = type.Name;
                target.SortOrder = type.SortOrder;
                _context.DocumentType.Update(target);
                _context.SaveChanges();
            }
            return AjaxResult.GetOK("保存成功！");
        }
        //删除文档类型
        public AjaxResult DeleteDocType(string id)
        {
            //首先判断此类型下面是否有文档
            var exist = _context.Document.Any(p => p.TypeId == id);
            if (exist)
            {
                return AjaxResult.GetError("当前类型下存在文档，请删除文档后再操作！");
            }

            DocumentType type = _context.DocumentType.Single(p => p.Id == id);
            type.Deleted = 1;
            _context.DocumentType.Update(type);
            _context.SaveChanges();

            return AjaxResult.GetOK("删除成功！");
        }


        //文档管理主页
        public IActionResult DocManageIndex()
        {
            var list = docService.GetDocumentTypeList();
            int? flag = HttpContext.Session.GetInt32("viewFlag");
            return View(Tuple.Create(list,flag));
        }
        //ajax 获取分页数据，文档类型
        public AjaxResult DocManageList(int page, int limit, string name,string typeId)
        {

            AjaxResult r = new AjaxResult();
            IQueryable<Document> q = _context.Document
                .Where(p => p.TypeId != null)
                .Where(p => p.DocState == 2); //上传完成并且保存的

            if (!string.IsNullOrWhiteSpace(name))
            {
                q = q.Where(p => p.Name.Contains(name));
            }

            if (!string.IsNullOrWhiteSpace(typeId))
            {
                q = q.Where(p => p.TypeId == typeId);
            }

            r.Count = q.Count();
            r.Code = 0;
            r.Data = q.Include(p=>p.Type).OrderBy(p => p.Name)
                .Skip((page - 1) * limit).Take(limit)
                .ToList();

            return r;
        }

        //文档批量上传页面
        public IActionResult DocBatchUpload()
        {
            var list = docService.GetDocumentTypeList();
            return View(list);
        }

        //批量保存上传的文件
        public AjaxResult BatchSaveUploadFile(string typeId,string[] list)
        {
            foreach(string id in list)
            {
                var doc = this.docService.GetById(id);
                doc.DocState = 2;
                doc.TypeId = typeId;
                _context.Document.Update(doc);
                _context.SaveChanges();
            }
            return AjaxResult.GetOK("操作成功！");
        }
    }
}
